var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
//var google = require('googleapis');
YouTube = require('youtube-api');
freebase = require('freebase');
//customsearch = require('customsearch');

var routes = require('./routes/index');
var users = require('./routes/users');
var results = require('./routes/results');

GoogleApiKey = 'AIzaSyBnVkWupXwU8by5zGpPBxdIh9h6P6hFTsA';
YouTube.authenticate({
    type: "key",
    key: GoogleApiKey
});

//google.auth.key = 'AIzaSyBnVkWupXwU8by5zGpPBxdIh9h6P6hFTsA';
//customsearch = google.customsearch('v1');


var app = express();




var youtubeApiFields = 'items(id,snippet/title, snippet/description,snippet/publishedAt,snippet/thumbnails/default,statistics/viewCount,statistics/likeCount,statistics/dislikeCount)';
var youtubeApiUrl = 'https://www.googleapis.com/youtube/v3/search?q=how+to+knitting&part=snippet&chart=mostPopular&maxResults=5&fields=items(id%2Csnippet(title%2Cdescription%2CpublishedAt%2Cthumbnails%2Fdefault))&key=AIzaSyDHbHnVs6jig5mVgNnXxQpQxDasYX12nsQ';


// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', routes);
app.use('/users', users);
app.use('/results', results);
app.use('/search', routes);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});


// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
    app.use(function(err, req, res, next) {
        res.status(err.status || 500);
        res.render('error', {
            message: err.message,
            error: err
        });
    });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
        message: err.message,
        error: {}
    });
});

app.listen(80);
module.exports = app;
